import { defineStore } from 'pinia';

// 确保在store初始化时能正确获取localStorage中的数据
const getStoredToken = () => {
  try {
    return localStorage.getItem('token') || null;
  } catch (error) {
    console.warn('获取localStorage中的token失败:', error);
    return null;
  }
};

const getStoredUserInfo = () => {
  try {
    const userInfo = localStorage.getItem('userInfo');
    return userInfo ? JSON.parse(userInfo) : null;
  } catch (error) {
    console.warn('获取localStorage中的userInfo失败:', error);
    return null;
  }
};

const getStoredUserPoints = () => {
  try {
    const points = localStorage.getItem('userPoints');
    console.log('从localStorage获取的用户积分:', points);
    // 如果没有存储积分，则初始化为0并存储
    if (points === null) {
      console.log('未找到存储的积分，初始化为0');
      localStorage.setItem('userPoints', '0');
      return 0;
    }
    return points ? parseInt(points) : 0;
  } catch (error) {
    console.warn('获取localStorage中的userPoints失败:', error);
    return 0;
  }
};


export const useUserStore = defineStore('user', {
  state: () => ({
    token: getStoredToken(),
    userInfo: getStoredUserInfo(),
    userPoints: getStoredUserPoints(),
  }),
  getters: {
    isLoggedIn: (state) => !!state.token,
  },
  actions: {
    setToken(token: string) {
      this.token = token;
      localStorage.setItem('token', token);
    },
    setUserInfo(userInfo: any) {
      this.userInfo = userInfo;
      localStorage.setItem('userInfo', JSON.stringify(userInfo));
    },
    setUserPoints(points: number) {
      console.log('设置用户积分:', points);
      this.userPoints = points;
      localStorage.setItem('userPoints', points.toString());
      console.log('localStorage中存储的用户积分:', localStorage.getItem('userPoints'));
    },
    
    // 初始化用户积分
    initUserPoints() {
      if (this.userPoints === 0 && localStorage.getItem('userPoints') === null) {
        this.setUserPoints(0);
      }
    },
    clearUser() {
      this.token = null;
      this.userInfo = null;
      this.userPoints = 0;
      localStorage.removeItem('token');
      localStorage.removeItem('userInfo');
      localStorage.removeItem('userPoints');
    },
  },
});